<template>
  <div id="bacTestResult">
    <vxe-toolbar class-name="bg-grey light">
      <template #buttons>
        <!-- <vxe-button type="text" class="button-blue margin-lr-xs" :content="'上一个'" @click="prevCLick()"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'下一个'" @click="nextCLick()"></vxe-button> -->
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'保存'" @click="saveBloodCultureInfo" :disabled="resultIsDisabled()"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'标签补打'" @click="openDialog"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'工作单'" @click="reprintLabel"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'初级报告'" @click="rptFirstReport" v-if="isShowFirstReport" :disabled="resultIsDisabled()||!isShowFirstReport"></vxe-button>
        <vxe-button type="text" class="button-red margin-lr-xs" class-name="margin-lr-xs" content="撤销报告" @click="cancelSecReport" v-if="isShowcancelFirstReport" :disabled='resultIsDisabled()||!isShowcancelFirstReport'></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'历史报告'" @click="rptFirstReportHistory"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="预览" @click="previewSecondRpt"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="打印" @click="printSecondRpt"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'转种'" @click="transplantationClick" :disabled="resultIsDisabled()"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'危急值'" @click="criticalClick"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'阴性结果'" @click="negativeResult" :disabled="resultIsDisabled()"></vxe-button>
        <vxe-button type="text" class="button-blue margin-lr-xs" :content="'72小时无菌发布'" @click="publish72NoGermReport" :disabled="resultIsDisabled()" :loading="publish72Loading"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="padding-top padding-lr flex justify-start solid lines-gray blod" style="height: 74px">
      <div v-for="(item, index) in culMediumList" :key="index" class="padding-lr selected-box flex justify-start" :class="curParentCulBox === index ? 'selected-box-active' : ''">
        <div class="bottle" @click="selectChangeCul(index, index, item)" v-if="item.mediumType === '2'" :style="{ background: item.mediumColor }">
          <div class="liquid text-xs text-cut text-red" style="height: 61%" :style="{ background: item.mediumColor }">
            <span class="text-bold text-black text-shadow" :style="{ background: item.mediumColor }">{{
              item.cultureBottle !== null ? item.cultureBottle : ''}}</span>
            <br /><span class="text-bold text-shadow text-sm margin-left-xs" v-if="item.isAlarm === 1">危</span>
            <br /><span class="text-bold text-shadow text-sm margin-left-xs" v-if="item.isPositive === 1">阳</span>
          </div>

          <div class="select-active bg-orange" v-if="curCulBox === index">
            <span class="vxe-icon-check"></span>
          </div>
        </div>
        <!-- 培养基开始 -->
        <div class="petri-dish" @click="selectChangeCul(index, index, item)" v-if="item.mediumType === '1'" :style="{ background: item.mediumColor }">
          <span class="text-bold text-black text-shadow">{{ item.cultureBottle !== null ? item.cultureBottle : '' }}</span>
          <br /><span class="text-bold text-shadow text-sm margin-left-xs" v-if="item.isAlarm === 1">危</span> <br /><span class="text-bold text-shadow text-sm margin-left-xs" v-if="item.isPositive === 1">阳</span>
          <div class="select-active bg-orange" v-if="curCulBox === index">
            <span class="vxe-icon-check"></span>
          </div>
        </div>
        <!-- 培养基结束 -->
        <!-- <span class="text-bold text-xl margin-lr-sm text-white" v-if="item && item.children && item.children.length > 0">→</span>
        <div style="height:100%;" class="flex justify-start" v-if="item && item.children && item.children.length > 0">
          <div class="bottle-chld margin-lr-xs" v-for="mc in item.children" :key="`${index}${mc.id}`" @click="selectChangeCul(index, `${index}${mc.id}`, mc)">
            <div class="liquid-chld text-xs text-cut text-red" style="height:61%">
              <span>血</span>
              <span>需氧</span>
            </div>

            <div class="select-active bg-orange" v-if="curCulBox === `${index}${mc.id}`">
              <span class="vxe-icon-check"></span>
            </div>
          </div>
        </div> -->
      </div>
    </div>
    <el-tabs v-model="activeName" type="card" class="lab-bac-test-result-tab el-tab-sm" @tab-click="tabHandleClick">
      <el-tab-pane label="培养过程" name="first"></el-tab-pane>
      <el-tab-pane label="过程记录" name="second">过程记录</el-tab-pane>
      <el-tab-pane label="流程单" name="third">流程单</el-tab-pane>
      <el-tab-pane label="申请项目" name="fourth"></el-tab-pane>
    </el-tabs>
    <Splitpanes horizontal v-if="activeName === 'first'" :dbl-click-splitter="false" style="height: calc(100% - 250px)">
      <Pane :size="paneTopSize">
        <Splitpanes :dbl-click-splitter="false">
          <Pane size="75">
            <el-scrollbar>
              <div class="padding-lr-xs form-panel flex justify-between" :class="(resultIsDisabled()||!isShowFirstReport) ? 'no-edit' : ''">
                <div style="width: 50%" class="padding-lr-sm">
                  <vxe-form ref="formObserRef" :data="formData" title-width="80" title-align="left">
                    <!-- 培养瓶、容器条码 -->
                    <vxe-form-item title="培养瓶" field="culMediumNa" span="24" :item-render="{}" title-overflow>
                      <template #default="params">
                        <vxe-input v-model="params.data.culMediumNa" v-enterNextResultInput class="enterNextResultInputFlag" placeholder="培养瓶" clearable></vxe-input>
                      </template>
                    </vxe-form-item>
                    <!-- 采样部位 -->
                    <vxe-form-item title="采样部位" field="result" span="24">
                      <template #default="params">
                        <!-- <vxe-input v-model="params.data.result" v-enterNextResultInput placeholder="采样部位" class="enterNextResultInputFlag" clearable @dblclick="selectBloodCulResult"></vxe-input> -->
                        <VxeDictSelection v-enterNextResultInput :isChild="false" :tableColumn="[
                          { field: 'code', title: '编码', width: `60px` },
                          { field: 'name', title: '名称', minWidth: `80px` }
                        ]" :url="`/api/sys/basDictDetail/findDictDetailList`" ref="dictpdownCYBW" @confirmClick="dropSelectConfirm" :aimKeys="[{ targetField: 'samplingSite', sourceField: 'code' }]" :displayTextObj="params.data.samplingSite" :dataObj="{ code: 'samplingSite' }">
                        </VxeDictSelection>
                      </template>
                    </vxe-form-item>
                    <!-- 血培养重量、报阳时长 -->
                    <vxe-form-item title="重量" field="weight" span="24" :item-render="{}" title-overflow>
                      <template #default="params">
                        <vxe-input v-model="params.data.weight" v-enterNextResultInput placeholder="重量" class="enterNextResultInputFlag" clearable></vxe-input>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="是否阳性" span="24">
                      <template #default="{ data }">
                        <vxe-radio-group v-model="data.isPositive" :strict="false" @change="valuePositiveChange($event, data.isPositive)">
                          <vxe-radio :label="1" content="阳性"></vxe-radio>
                          <vxe-radio :label="0" content="阴性"></vxe-radio>
                        </vxe-radio-group>
                      </template>
                    </vxe-form-item>

                    <vxe-form-item title="鉴定结果" span="24">
                      <template #title>
                        <span>鉴定结果</span>
                      </template>
                      <template #default="params">
                        <VxePulldownSelectionWithNa v-if="formData.isPositive == 0" style="width: 100%" :isChild="false" :url="'/api/bac/bac-desc-option/findBacDescOptionList'" @confirmClick="SelectRowResultClick" :tableColumn="[
                            { type: 'seq', title: '#', width: '30px' },
                            { field: 'optNa', title: '名称' },
                            { field: 'optNo', title: '编码' }
                          ]" :aimKeys="[{ aimKey: 'result', rowKey: 'optNa' }]" :displayTexts="['result']" :displayTextObj="params.data.result ? params.data.result : ''" />

                        <vxe-input v-model="params.data.result" v-else v-enterNextResultInput placeholder="" class="enterNextResultInputFlag" clearable></vxe-input>
                      </template>
                    </vxe-form-item>

                    <!-- 培养结果 -->
                    <!-- <vxe-form-item title="培养结果" field="result" span="24">
                      <template #default="params">
                        <vxe-input v-model="params.data.result" v-enterNextResultInput placeholder="培养结果(双击选择)" class="enterNextResultInputFlag" clearable @dblclick="selectBloodCulResult"></vxe-input>
                      </template>
                    </vxe-form-item> -->
                    <vxe-form-item :title="formData.isPositive == 1 ? '报阳时长' : '培养时长'" field="expoTime" span="24" :item-render="{}" title-overflow>
                      <template #default="params">
                        <vxe-input v-model="params.data.expoTime" v-enterNextResultInput placeholder="培养时长" class="enterNextResultInputFlag" clearable></vxe-input>
                      </template>
                    </vxe-form-item>
                    <vxe-form-gather span="24">
                      <vxe-form-item title="特殊描述" field="specialDesc" span="24" :item-render="{}" title-overflow>
                        <template #default="params">
                          <vxe-input v-model="params.data.specialDesc" v-enterNextResultInput placeholder="特殊描述" class="enterNextResultInputFlag" clearable></vxe-input>
                        </template>
                      </vxe-form-item>
                    </vxe-form-gather>

                    <vxe-form-gather span="24">
                      <vxe-form-item title="危急值信息" field="alarmText" span="24" :item-render="{}" title-overflow>
                        <template #title>
                          <vxe-checkbox v-model="formData.isAlarm" :checked-value="1" :unchecked-value="0">危急值</vxe-checkbox>
                        </template>
                        <template #default="params">
                          <!-- <vxe-textarea v-enterNextResultInput v-model="params.data.obserDesc" placeholder="形态描述" @dblclick="dblclickSelectObsers"></vxe-textarea> -->
                          <VxeRemarkDictSelection :isChild="false" :tableColumn="[
                            { field: 'code', title: '编码', width: `60px` },
                            { field: 'name', title: '名称', minWidth: `80px` }
                          ]" :url="`/api/sys/basDictDetail/findDictDetailList`" ref="dictpdownPYX" @confirmClick="remarkConfirm" :aimKeys="[{ targetField: '', sourceField: 'name' }]" :displayTextObj="params.data.alarmText" :dataObj="{ code: 'cultureAlarm' }">
                          </VxeRemarkDictSelection>
                        </template>
                      </vxe-form-item>
                    </vxe-form-gather>
                  </vxe-form>
                </div>
                <div style="width: 50%" class="padding-lr-sm">
                  <vxe-form ref="formObserRef" :data="formData" title-width="90" title-align="right">
                    <vxe-form-gather span="24">
                      <vxe-form-item title="培养箱" field="instrCode" span="24">
                        <template #default="params">
                          <!-- <VxeRemarkDictSelection :isChild="false" :tableColumn="[{ field: 'code', title: '编码', width: `60px` },{ field: 'name', title: '名称', minWidth: `80px` }]" :url="`/api/sys/basDictDetail/findDictDetailList`" ref="dictpdownPYX" @confirmClick="remarkConfirm" :aimKeys="[{ targetField: '', sourceField: 'name' }]" :dataObj="{ code: 'incubator' }"></VxeRemarkDictSelection> -->
                          <VxeDictSelection v-enterNextResultInput :isChild="false" :tableColumn="[
                            { field: 'code', title: '编码', width: `60px` },
                            { field: 'name', title: '名称', minWidth: `80px` }
                          ]" :url="`/api/sys/basDictDetail/findDictDetailList`" ref="dictpdownCYBW" @confirmClick="dropSelectConfirm" :aimKeys="[{ targetField: 'instrCode', sourceField: 'code' }]" :displayTextObj="params.data.instrCode" :dataObj="{ code: 'incubator' }"></VxeDictSelection>
                        </template>
                      </vxe-form-item>
                      <vxe-form-item title="瓶号" field="bottleNo" span="24" :item-render="{}" title-overflow>
                        <template #default="params">
                          <vxe-input v-model="params.data.bottleNo" v-enterNextResultInput placeholder="瓶号" class="enterNextResultInputFlag" clearable></vxe-input>
                        </template>
                      </vxe-form-item>
                      <vxe-form-item title="位置" field="posInfo" span="24" :item-render="{}" title-overflow>
                        <template #default="params">
                          <vxe-input v-model="params.data.posInfo" v-enterNextResultInput placeholder="位置" class="enterNextResultInputFlag" clearable></vxe-input>
                        </template>
                      </vxe-form-item>
                    </vxe-form-gather>
                    <vxe-form-gather span="24">
                      <vxe-form-item title="状态" field="state" span="24" :item-render="{}" title-overflow>
                        <template #default="params">
                          <vxe-input v-model="params.data.state" v-enterNextResultInput placeholder="状态" class="enterNextResultInputFlag" clearable></vxe-input>
                        </template>
                      </vxe-form-item>
                      <vxe-form-item title="开始培养时间" field="testTime" span="24" :item-render="{}" title-overflow>
                        <template #default="params">
                          <vxe-input v-model="params.data.testTime" v-enterNextResultInput placeholder="进箱时间" type="datetime" transfer class="enterNextResultInputFlag" clearable @change="expoTimeDiffChange"></vxe-input>
                        </template>
                      </vxe-form-item>
                      <vxe-form-item title="结束培养时间" field="resultTime" span="24" :item-render="{}" title-overflow>
                        <template #default="params">
                          <vxe-input v-model="params.data.resultTime" v-enterNextResultInput placeholder="出箱时间" type="datetime" transfer class="enterNextResultInputFlag" clearable @change="expoTimeDiffChange"></vxe-input>
                        </template>
                      </vxe-form-item>
                      <vxe-form-item title="销毁时间" field="destructionTime" span="24" :item-render="{}" title-overflow>
                        <template #default="params">
                          <vxe-input v-model="params.data.destructionTime" v-enterNextResultInput placeholder="销毁时间" type="datetime" transfer class="enterNextResultInputFlag" clearable></vxe-input>
                        </template>
                      </vxe-form-item>
                      <vxe-form-item title="" field="isPollute" span="12" :item-render="{}" title-overflow>
                        <template #default="params">
                          <vxe-checkbox v-model="params.data.isPollute" :checked-value="1" :unchecked-value="0">标本污染</vxe-checkbox>
                        </template>
                      </vxe-form-item>
                    </vxe-form-gather>
                  </vxe-form>
                </div>
              </div>
            </el-scrollbar>
          </Pane>
          <Pane size="25">
            <Splitpanes horizontal>
              <Pane size="50">
                <div class="text-bold margin-left-xs">
                  <span class="bg-gray text-df padding-lr-xs radius">箱号</span><span style="min-width: 100px !important; width: 100%" class="bg-orange padding-lr-sm text-df margin-left-xs radius light">{{ formData.posCol }}</span>
                </div>
                <div class="text-bold margin-left-xs">
                  <span class="bg-gray text-df padding-lr-xs radius">架号</span><span style="min-width: 100px !important; width: 100%" class="bg-blue padding-lr-sm text-df margin-left-xs radius light">{{ formData.posRow }}</span>
                </div>
              </Pane>
              <Pane size="50">
                <div class="text-bold text-shadow">培养曲线</div>
                <div class="block margin-top">
                  <el-image v-if="formData.cultureCurveUrls" class="img-no-drag" :src="formData.cultureCurveUrls" />
                </div>
              </Pane>
            </Splitpanes>
          </Pane>
        </Splitpanes>
      </Pane>
      <Pane :size="100 - paneTopSize" :max-size="100 - paneTopSize" :min-size="100 - paneTopSize">
        <BacHistories ref="BacHistoriesRef" />
      </Pane>
    </Splitpanes>
    <BacProcessRecords ref="BacProcessRecordsRef1" v-if="activeName === 'second'" :businessType="'node1'" />
    <Cost ref="costRef" v-show="activeName === 'fourth'" />
    <BacFirstReport ref="BacFirstReportRef" />
    <!-- 血培养结果选择 -->
    <vxe-modal v-model="bloodCulResultModal" width="25vw" height="35vh" show-footer :mask="false">
      <template #title>
        <span>培养结果</span>
      </template>
      <template #default>
        <div class="form-panel">
          <vxe-form :data="formData" title-width="80">
            <vxe-form-item title="培养结果" span="24">
              <template #default="{ data }">
                <vxe-radio-group v-model="data.isPositive" :strict="false" @change="valuePositiveChange($event, data.isPositive)">
                  <vxe-radio :label="1" content="阳性"></vxe-radio>
                  <vxe-radio :label="0" content="阴性"></vxe-radio>
                </vxe-radio-group>
              </template>
            </vxe-form-item>
            <vxe-form-item title="报阳时长" span="24">
              <template #default="{ data }">
                <vxe-input v-model="data.expoTime" placeholder="默认尺寸"></vxe-input>
              </template>
            </vxe-form-item>

            <vxe-form-item title="鉴定结果" span="24" v-if="formData.isPositive == 0">
              <template #title>
                <span style="color: red">鉴定结果</span>
              </template>
              <template #default="params">
                <VxePulldownSelectionWithNa style="width: 100%" :isChild="false" :url="'/api/bac/bac-desc-option/findBacDescOptionList'" @confirmClick="SelectRowResultClick" :tableColumn="[
                    { type: 'seq', title: '#', width: '30px' },
                    { field: 'optNa', title: '名称' },
                    { field: 'optNo', title: '编码' }
                  ]" :aimKeys="[{ aimKey: 'result', rowKey: 'optNa' }]" :displayTexts="['result']" :displayTextObj="params.data.result ? params.data.result : ''" />
              </template>
            </vxe-form-item>
          </vxe-form>
        </div>
      </template>
      <template #footer>
        <vxe-button @click="bloodCulResultModal = false">关闭</vxe-button>
        <vxe-button type="text" class="button-blue margin-left-sm" @click="bloodCulResultModal = false" content="确定"></vxe-button>
      </template>
    </vxe-modal>
    <!-- 转种弹窗 -->
    <vxe-modal v-model="culCombinaModal" width="65vw" height="55vh" show-footer :mask="false">
      <template #title>
        <span>培养基组合选择</span>
      </template>
      <template #default>
        <vxe-toolbar>
          <template #buttons>
            <vxe-radio-group v-model="culCombinaType" @change="culCombinaSelectChange">
              <vxe-radio-button label="-1" content="全部"></vxe-radio-button>
              <vxe-radio-button label="0" content="普通"></vxe-radio-button>
              <vxe-radio-button label="1" content="纯分"></vxe-radio-button>
              <vxe-radio-button label="2" content="转种"></vxe-radio-button>
            </vxe-radio-group>
          </template>
          <template #tools>
            <div class="flex justify-end form-panel">
              <vxe-input v-model="culCombinaSearchKeyValue" clearable placeholder="培养基组合、名称、输入码" style="width: 300px" @keyup="keyupEventByCulCombinaKeyValue"></vxe-input>
            </div>
          </template>
        </vxe-toolbar>
        <div style="height: calc(100% - 40px)">
          <vxe-table ref="culCombinaTableRef" :loading="culCombinaLoading" :data="culCombinaSelectList" height="auto" :border="'inner'" :column-config="{ resizable: true }" :row-config="{ isCurrent: true, isHover: true }">
            <vxe-column type="seq" width="30"></vxe-column>
            <vxe-column field="code" title="组合代码" width="80"></vxe-column>
            <vxe-column field="name" title="组合名称" min-width="100"></vxe-column>
            <vxe-column field="remark" title="备注" width="200"></vxe-column>
            <vxe-column field="inputCode" title="输入码" width="100"></vxe-column>
            <vxe-column field="orderNum" title="序号" width="60"></vxe-column>
          </vxe-table>
        </div>
      </template>
      <template #footer>
        <vxe-button @click="culCombinaModal = false">关闭</vxe-button>
        <vxe-button type="text" class="button-blue margin-left-sm" @click="culCombinaComfirm" content="确定"></vxe-button>
      </template>
    </vxe-modal>

    <el-dialog title="培养基" :show-close="false" v-model="dialog" append-to-body width="1000px" :close-on-click-modal="false">
      <!-- <vxe-toolbar perfect>
        <template #buttons>
          <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="getCultureDetail"></vxe-button>
        </template>
      </vxe-toolbar> -->
      <div class="tableBody">
        <vxe-table ref="cultureTableRef" class="mytable-scrollbar" border="inner" align="left" height="500" :data="cultureTableList" :loading="lloading" :column-config="{ resizable: true }" resizable show-overflow keep-source>
          <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
          <vxe-column type="seq" title="序号" width="30"></vxe-column>
          <vxe-column field="sampleNo" title="标本号" align="center"></vxe-column>
          <vxe-column field="reqNo" title="条码号" align="center"></vxe-column>
          <vxe-column field="cultureNo" title="编号" align="center"></vxe-column>
          <vxe-column field="cultureNa" title="名称"></vxe-column>
        </vxe-table>
      </div>
      <div class="dialog-footer flex right justify-end" style="margin-top: 10px;">
        <el-button type="primary" @click="printLabel">确定</el-button>
        <el-button @click="closeDialog()">取消</el-button>
      </div>
    </el-dialog>

    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    <!-- 设置菌落形态 -->
    <BacObserSelection ref="BacObserSelectionRef" @obserConfirm="obserConfirm" :isShowCulMediumBox="false" />

    <!-- 危机值上报 -->
    <BacCriticalBloodReport ref="criticalBloodReportRef" @treatFinish="alarmTreatFinish" />
    <!-- 阴性结果 -->
    <RptResultNegativeForm ref="RptResultBacFormRef" @confirmSave="bacTestResultConfirmSave" />
    <!-- 初级报告发布历史 -->
    <BacFirstReportHistory ref="BacFirstReportHistoryRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, getCurrentInstance, defineProps } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { LabMainInfoBacBtns } from '../LabMainInfoBacUtils';
import { formatDateTime, IsEmpty, calculateTimeDifference } from '@/utils/common';
import VxePulldownSelectionByDictType from '@/components/VxePulldownSelectionByDictType.vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';
import { AppStore } from '@/stores/store';
import { SysOptions } from '@/stores/sysoptions';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue'; //WithNa
import BacHistories from './BacHistories.vue';
import BacProcessRecords from './BacProcessRecords.vue';
import Cost from './Cost.vue';
import BacFirstReport from './BacFirstReport.vue';
import BacFirstReportHistory from './BacFirstReportHistory.vue';
import QuietPrint from '@/components/QuietPrint.vue'; /**静默打印组件 */
import BacObserSelection from './BacObserSelection.vue'; /**菌落形态结果选择 */
import BacCriticalBloodReport from '@/views/lab_sys/bac_bus/components/BacCriticalBloodReport.vue'; //危急值上报
import RptResultNegativeForm from './RptResultNegativeForm.vue'; /**细菌阴性结果表单 */
import VxeRemarkDictSelection from '@/components/VxeRemarkDictSelection.vue';
import VxeDictSelection from '@/components/VxeDictSelection.vue';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';
import { saveProcessLogs } from '@/utils/BacProcessLogHelper';
import { clear } from 'xe-utils';
import { getOptionValueByCodeRptGroupOption, getOptionValueByCodeGlobalOption } from '@/utils/SysOptionsHelper';

defineExpose({ initPage, initTestList, drugResultTempLdateQuickInsert /**药敏模板快速输入 */ });
const BacObserSelectionRef = ref(null); /**设置菌落形态弹窗选择对象 */
let printParamsObj = ref(null); /**静默打印参数 */
let quietPrintRef: any = ref<InstanceType<typeof quietPrintRef>>();
const storeObj = AppStore();
const sysoptionObj = SysOptions(); //系统参数状态管理对象
let { proxy }: any = getCurrentInstance();
const labmaininfobacbtns = ref(LabMainInfoBacBtns());
const bacTestResultRef = ref(null); /**细菌结果列表对象 */
const bacDrugTestResultRef = ref(null); /**药敏结果列表对象 */
const formObserRef: any = ref(null); /**菌落形态观察结果表单对象 */
const BacHistoriesRef = ref(null); /**多少天内结果组件对象 */
const BacProcessRecordsRef1 = ref(null); /**过程记录对象 */
const criticalBloodReportRef = ref(null); /**危急值上报 */
let costRef: any = ref(null); //费用传值
let stepNodeObj: any = reactive({}); /**当前选中流程节点对象 */
let BacFirstReportRef = ref(null); /**初级报告弹窗对象 */
let BacFirstReportHistoryRef = ref(null); /** 初级报告历史弹窗对象*/
let publish72Loading = ref(false);
const RptResultBacFormRef = ref(null); /**阴性结果表单对现象 */
const props = defineProps({
  tabs: {
    type: Array,
    default: reactive([
      {
        title: 'Step 1',
        iconSuccess: null,
        isValid: true
      },
      {
        title: 'Step 2',
        iconSuccess: null,
        isValid: true
      },
      {
        title: 'Step 3',
        iconSuccess: null,
        isValid: true
      }
    ])
  }
});
let curTestFlowObj = reactive({}); /**当前选中方案对象 */
let curTestNodeObj = reactive({}); /**当前选中节点对象 */
let layout: any[] = reactive([]); /**栅格布局数组 */
let bacActive = ref(3); /**当前选中第几珠菌 */
let formData: any = reactive({ val1: '', val2: '', val3: '', val4: '' }); /**菌落形态观察结果表单 */
let isDescOptionResultFlag = ref(false); /**是否描述性结果 */
let labMainInfoObj: any = reactive({}); /**检验记录当前选中对象 */
let sltWorkFlowObj: any = reactive({}); /**当前选中流程节点对象 */
let bacTestResultObj: any = reactive({}); /**细菌检验结果 */
let wkFlwNodeObj: any = reactive({}); /**工作流程节点对象 */
let bacTestResult: any[] = reactive([]); /**细菌检测结果列表 */
let bacDrugTestResult: any[] = reactive([]); /**细菌药敏检测结果 */
let form: any = reactive({ autocalc: false });
let activeName = ref('first');
let paneTopSize = ref(70);
let paneBottomSize = ref(30);
let curBacTestResult: any = reactive({}); /**细菌鉴定结果列表行选中 */
let culGridColumnLayout = reactive([]); /**栅格布局列数量 */
let culGridRowLayout = reactive([]); /**栅格布局行数量 */
let curCulBox = ref(0); /**选中的培养瓶 */
let curParentCulBox = ref(0); /**培养瓶父容器 */
let culMediumList = reactive([]); /**培养基集合 */
let curCulBoxObj = reactive({}); /**当前选中瓶子 */
let bloodCulResultModal = ref(false); /**培养结果弹窗 */
let culCombinaModal = ref(false); /**培养基组合弹窗 */
let culCombinaType = ref('2'); /**培养基组合类型 */
let culCombinaSearchKeyValue = ref(''); /**培养基组合选择关键字查询 */
let culCombinaSelectList = reactive([]); /**培养基组合选择列表集合 */
let culCombinaLoading = ref(false); /**加载培养基组合 */
let culCombinaTableRef = ref(null); /**培养基组合列表对象 */

let cultureTableList: any = reactive([]); //弹出框List
let lloading = ref(false); //加载状态
let dialog = ref(false); //添加弹框展示状态

//#region  计算属性

//#region  自定义指令
// 自定义指令
const enterNextResultInput: ObjectDirective<HTMLElement> = {
  mounted(el) {
    el.addEventListener('keypress', (e) => {
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      if (charcode == 13) {
        const doms: any = document.getElementsByClassName('enterNextResultInputFlag');
        let list = [];
        for (let i = 0; i < doms.length; i++) {
          let node = doms[i].childNodes;
          if (node.length > 0) {
            node.forEach((v) => {
              if ((v.nodeName == 'TEXTAREA' || v.nodeName == 'INPUT') && !v.disabled) {
                list.push(v);
              }
            });
          }
        }
        for (let j = 0; j <= list.length; j++) {
          if (list[j] == document.activeElement) {
            if (j == list.length - 1) {
              return;
            }
            list[j + 1].focus();
            return;
          }
        }
      }
    });
  }
};

// 使用自定义指令
proxy.$.directives = { enterNextResultInput: enterNextResultInput };
//#endregion

/**是否关闭初审按钮 */
let isVisiableFChkBtn = computed(() => {
  const a = sysoptionObj.globalOptions.filter((p: any) => p.field === 'ishidefirstchk');
  if (a && a.length > 0 && a[0] && !IsEmpty(a[0].value)) {
    return IsEmpty(a[0].value) ? false : a[0].value === '1' || a[0].value === 1 ? true : false;
  }
  return false;
});
/**病历按钮显示文字(等于-时隐藏) */
let dzblBtnText = computed(() => {
  const a = sysoptionObj.globalOptions.filter((p: any) => p.field === 'blbtntxt');
  if (a && a.length > 0 && a[0] && !IsEmpty(a[0].value)) {
    return IsEmpty(a[0].value) ? '' : a[0].value === '-' ? '' : a[0].value;
  }
  return '';
});
//#endregion

/**初始化界面 */
function initPage(mainInfoRow: any, stepNode: any, sltWorkFlow: any) {
  Object.assign(labMainInfoObj, mainInfoRow);
  Object.assign(sltWorkFlowObj, sltWorkFlow);
  getBacHistories();
  findBloodCulMediumList(); /**加载培养基 */
}
//历史回顾传值
function getBacHistories() {
  BacHistoriesRef.value?.initPage(labMainInfoObj);
}

function tabHandleClick(tab) {
  if (tab.paneName === 'second' || tab.paneName.value === 'second') {
    setTimeout(() => {
      if (BacProcessRecordsRef1.value) {
        BacProcessRecordsRef1.value?.initRecords(labMainInfoObj, stepNodeObj);
      }
    }, 200);
  } else if (tab.paneName === 'fourth') {
    costRef.value.getreqDetail(labMainInfoObj);
  }
}

// 接收父组件传值
function initTestList(repData: any, isCbUptMainInfo = true) {
  if (IsEmpty(repData) || !repData) {
    resultList.length = 0;
    return;
  }

  Object.assign(labMainInfoObj, repData);
  findBacBloodCultureResult();
}

//上一个
function prevCLick() {
  actionCLick({ event: 'prevCode' });
}
//下一个
function nextCLick() {
  actionCLick({ event: 'nextCode' });
}

function actionCLick(item) {
  proxy.$emit('actionBtnsClick', item);
}
/**清空表单 */
function clearFormData() {
  formData.alarmText = '';
  formData.barcode = '';
  formData.bottleNo = '';
  formData.createTime = '';
  formData.creator = '';
  formData.culMediumNa = '';
  formData.culMediumNo = '';
  formData.culbottleNo = '';
  formData.cultureCurveUrls = '';
  formData.cultureTime = '';
  formData.delFlag = '';
  formData.destructionTime = '';
  formData.editTime = '';
  formData.editor = '';
  formData.expoTime = '';
  formData.id = '';
  formData.instrCode = '';
  formData.instrNa = '';
  formData.isAlarm = 0;
  formData.isPositive = 0;
  formData.isPollute = 0;
  formData.obserDesc = '';
  formData.orgId = '';
  formData.posCol = '';
  formData.posInfo = '';
  formData.posRow = '';
  formData.reqNo = '';
  formData.result = '';
  formData.resultTime = '';
  formData.rptGroup = '';
  formData.sampleNo = '';
  formData.sampleda = '';
  formData.samplingSite = '';
  formData.samplingSiteNa = '';
  formData.specialDesc = '';
  formData.state = '';
  formData.strainCount = '';
  formData.testFlowNo = '';
  formData.testNodeNo = '';
  formData.testTime = '';
  formData.weight = '';
}
/**查询细菌检测结果 */
function findBacBloodCultureResult() {
  bacTestResult.length = 0;
  bacDrugTestResult.length = 0;

  if (IsEmpty(labMainInfoObj.id)) {
    return;
  }
  //clear(formData);
  clearFormData();
  const url = '/bac-blood-cultrue/findLastoneBacBloodCultrueList';
  let data = { maininfoId: labMainInfoObj.id, rptGroup: labMainInfoObj.rptGroup, sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'), sampleNo: labMainInfoObj.sampleNo, testFlowNo: '', testNodeNo: '', culMediumNo: curCulBoxObj.cultureNo } as any;
  // if (!IsEmpty(wkFlwNodeObj.id)) {
  //   data['wkFlwId'] = wkFlwNodeObj.workFlowId;
  //   data['wkFlwNodeId'] = wkFlwNodeObj.id;
  // }

  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res && res.data) {
        Object.assign(formData, res.data);
        formData.barcode = curCulBoxObj.barcode;
        formData.bottleNo = IsEmpty(formData.bottleNo) ? curCulBoxObj.barcode : formData.bottleNo;
        formData.culMediumNa = IsEmpty(formData.culMediumNa) ? curCulBoxObj.cultureNa : formData.culMediumNa;
      } else {
        formData.barcode = curCulBoxObj.barcode;
        formData.bottleNo = curCulBoxObj.barcode;
        formData.culMediumNa = curCulBoxObj.cultureNa;
      }
      if (IsEmpty(formData.testTime) || IsEmpty(formData.resultTime) || IsEmpty(formData.expoTime)) {
        let s = IsEmpty(formData.testTime) ? labMainInfoObj.testTime : formData.testTime;
        let e = IsEmpty(formData.resultTime) ? formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss') : formData.resultTime;
        let diffObj = calculateTimeDifference(s, e);
        formData.expoTime = `${!IsEmpty(diffObj.days) ? diffObj.days + '天' : ''}${!IsEmpty(diffObj.hours) ? diffObj.hours + '时' : ''}${!IsEmpty(diffObj.minutes) ? diffObj.minutes + '分' : ''}`;
      }
      if (!IsEmpty(formData.destructionTime) && formatDateTime(formData.destructionTime, 'yyyy-MM-dd') === '1900-01-01') {
        formData.destructionTime = '';
      }
      //判断是否展示初级报告
      if (!IsEmpty(formData) && formData.bacPublishStatus == 1) {
        isShowFirstReport.value = false;
        isShowcancelFirstReport.value = true;
      } else {
        isShowFirstReport.value = true;
        isShowcancelFirstReport.value = false;
      }
    })
    .catch((err: any) => {});
}
let isShowFirstReport = ref(false);
let isShowcancelFirstReport = ref(false);

/**查询细菌检测结果 */
function findBacDrugTestResult(bacTestResult) {
  bacDrugTestResult.length = 0;
  if (IsEmpty(bacTestResult.id)) {
    return;
  }
  const url = '/api/bac/bac-drug-test-result/findBacDrugTestResultList';
  let data = { maininfoId: labMainInfoObj.id, bacTestResultId: bacTestResult.id } as any;
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res && res.data && res.data.length >= 0) {
        bacDrugTestResult.length = 0;
        Object.assign(bacDrugTestResult, res.data);
        bacDrugTestResult.value?.setCurrentRow(res.data[0]);
      }
    })
    .catch((err: any) => {});
}
/**设置表头单元格样式 */
function setBacDrugTestResultHeaderCellStyle({ column }) {
  if (column.field === 'r' || column.field === 'i' || column.field === 'sdd' || column.field === 's' || column.field === 'ecoff' || column.field === 'whonetTest' || column.field === 'breakPointRef' || column.field === 'guideline' || column.field === 'year' || column.field === 'germCodeType' || column.field === 'orgCodeType' || column.field === 'germNo' || column.field === 'breakPointType' || column.field === 'host' || column.field === 'infeSite' || column.field === 'refTable' || column.field === 'refTableSeq' || column.field === 'breakPointId') {
    return { fontWeight: 300 };
  }
}
/** 细菌检测结果列表单元格样式*/
function setBacTestResultCellStyle({ row, column }) {
  if (column.field === 'wkFlwId') {
    return { backgroundColor: '#409eff', height: '100%' };
  }
  return null;
}
/**新增鉴定结果 */
async function insertBacTestResult(isDescOptionsResult = false) {
  if (IsEmpty(labMainInfoObj.sampleda) || IsEmpty(labMainInfoObj.rptGroup) || IsEmpty(labMainInfoObj.sampleNo) || IsEmpty(labMainInfoObj.id)) {
    VxeMessage('请先选中上机记录', VxeNotifyType.warning);
    return;
  }
  const userInfo = localStorage.getItem('userInfo');
  const userInfoObj = JSON.parse(userInfo);
  isDescOptionResultFlag.value = isDescOptionsResult;
  let row = {
    id: '',
    wkFlwId: '',
    isolateNum: null,
    germNo: '',
    germNa: '',
    testResult: '',
    resiPhenNa: '',
    urinColoCount: null,
    infeSiteNa: '',
    operateDate: formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss'),
    operateUserNo: userInfoObj ? userInfoObj.realname : '',
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd hh:mm:ss'),
    rptGroup: labMainInfoObj.rptGroup,
    sampleNo: labMainInfoObj.sampleNo,
    maininfoId: labMainInfoObj.id
  };
  bacTestResult.push(row);
  await bacTestResultRef.value?.setCurrentRow(row);
  await bacTestResultRef.value?.setEditCell(row, 'germNa');
  setTimeout(() => {
    bacTestResultRef.value?.scrollToRow(row);
  }, 100);
}
/**新增抗生素结果 */
async function insertBacDrugTestResult() {
  if (IsEmpty(curBacTestResult.id)) {
  }
  let row = {
    id: '',
    bacTestResultId: curBacTestResult.id,
    isReport: 0,
    wkFlwId: '',
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd hh:mm:ss'),
    rptGroup: labMainInfoObj.rptGroup,
    sampleNo: labMainInfoObj.sampleNo,
    maininfoId: labMainInfoObj.id,
    antRecomGroupNa: '',
    antNo: '',
    antNa: '',
    potency: '',
    drugTestMethNa: '',
    testResult: '',
    interpNa: '',
    breakPoint: '',
    isNaturlResis: 0,
    r: '',
    i: '',
    sdd: '',
    s: '',
    ecoff: '',
    whonetTest: '',
    breakPointRef: '',
    guideline: '',
    year: '',
    germCodeType: '',
    germNo: '',
    breakPointType: '',
    host: '',
    infeSite: '',
    refTable: '',
    refTableSeq: '',
    breakPointId: '',
    isolateNum: null,
    germNa: '',
    //testResult: '',
    resiPhenNa: '',
    urinColoCount: null,
    infeSiteNa: ''
  };
  bacDrugTestResult.push(row);
  await bacDrugTestResultRef.value?.setCurrentRow(row);
  await bacDrugTestResultRef.value?.setEditCell(row, 'antNa');
  setTimeout(() => {
    bacDrugTestResultRef.value?.scrollToRow(row);
  }, 100);
}
/**微生物结果选择确认事件 */
function bacTestResultConfirmClick(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      bacTestResult[e.childIndex][m.formKey] = e.row[m.rowKey];
    });
  }
}
/**描述性结果选择确认 */
function SelectRowClick(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      bacTestResult[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
function SelectRowResultClick(e) {
  formData.result = e.row.optNa;
}

function valuePositiveChange(e, f = null) {
  if (f == 1) {
    formData.result = '阳性';
    formData.isAlarm = 1;
    formData.alarmText = '阳性结果';
  } else {
    formData.result = '';
    formData.isAlarm = 0;
    formData.alarmText = '';
  }
}

/**抗生素结果确认事件 */
function bacDrugResultConfirmClick(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      bacDrugTestResult[e.childIndex][m.formKey] = e.row[m.rowKey];
    });
  }
}
/**细菌结果列表关闭编辑状态 */
function bacTestResultEditClosed({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  let url = `/api/bac/bac-test-result/${row && !IsEmpty(row.id) ? 'updateBacTestResult' : 'addBacTestResult'}`;
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      Object.assign(bacTestResult[rowIndex], res.data);
    })
    .catch((err: any) => {
      //ToDo
    });
}
/**药敏鉴定结果列表关闭编辑状态 */
function bacDrugTestResultEditClose({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  let url = `/api/bac/bac-drug-test-result/${row && !IsEmpty(row.id) ? 'updateBacDrugTestResult' : 'addBacDrugTestResult'}`;
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      Object.assign(bacDrugTestResult[rowIndex], res.data);
    })
    .catch((err: any) => {
      //ToDo
    });
}
/**细菌列表行选择改变 */
function bacTestResultSelectChange({ row }) {
  Object.assign(curBacTestResult, row);
  bacDrugTestResult.length = 0;
  findBacDrugTestResult(curBacTestResult);
}
/**药敏鉴定结果 刷新按钮刷新 */
function bacDrugTestResultRefresh() {
  findBacDrugTestResult(curBacTestResult);
}
/**删除细菌鉴定结果 */
async function deletebacTestResult() {
  const row = bacTestResultRef.value?.getCurrentRecord();
  if (IsEmpty(row) || IsEmpty(row.id)) {
    VxeMessage('请先选中要删除的行', VxeNotifyType.warning);
    return;
  }
  const type = await VXETable.modal.confirm('确定删除选中记录?'); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    let url = `/api/bac/bac-test-result/deleteBacTestResult`;
    proxy.$http
      .post(url, row)
      .then(async (res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
          const ci = bacTestResultRef.value?.getRowIndex(row);
          await bacTestResultRef.value?.remove(row);
          bacTestResult.splice(ci, 1);
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('删除失败', VxeNotifyType.error);
      });
  }
}
/**删除药敏检验结果 */
async function deleteBacDrugTestResult() {
  const row = bacDrugTestResultRef.value?.getCurrentRecord();
  if (IsEmpty(row) || IsEmpty(row.id)) {
    VxeMessage('请先选中要删除的行', VxeNotifyType.warning);
    return;
  }
  const type = await VXETable.modal.confirm('确定删除选中记录?'); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    let url = `/api/bac/bac-drug-test-result/deleteBacDrugTestResult`;
    proxy.$http
      .post(url, row)
      .then(async (res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
          const ci = bacDrugTestResultRef.value?.getRowIndex(row);
          await bacDrugTestResultRef.value?.remove(row);
          bacDrugTestResult.splice(ci, 1);
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('删除失败', VxeNotifyType.error);
      });
  }
}
/**选择药敏模板 */
function insertBacDrugResultTemplate() {
  proxy.$emit('selectBacDrugResultTemplate');
}
/**药敏模板快速输入 */
function drugResultTempLdateQuickInsert(rows) {
  const curTestResultObj = bacTestResultRef.value?.getCurrentRecord();
  let url = `/api/bac/bac-drug-test-result/drugResultTemplateQuickInsert`;
  proxy.$http
    .post(url, { mainInfoId: labMainInfoObj.id, bacTestResultId: curTestResultObj.id, bacDrugResultTemplates: rows })
    .then(async (res: any) => {
      if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
        findBacDrugTestResult(curTestResultObj);
        VxeMessage(res.status.msg, VxeNotifyType.success);
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('删除失败', VxeNotifyType.error);
    });
}
/**批量删除药敏结果 */
async function deleteAll() {
  const type = await VXETable.modal.confirm('确定全部删除记录?'); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    let url = `/api/bac/bac-drug-test-result/batchDeleteBacDrugTestResult`;
    proxy.$http
      .post(url, bacDrugTestResult)
      .then((res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
          const curTestResultObj = bacTestResultRef.value?.getCurrentRecord();
          findBacDrugTestResult(curTestResultObj);
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('删除失败', VxeNotifyType.error);
      });
  }
}
/**保存培养结果 */
function saveBloodCultureInfo() {  
  formData.culMediumNo = curCulBoxObj.cultureNo;
  formData.sampleNo = labMainInfoObj.sampleNo; //样本号
  formData.sampleda = labMainInfoObj.sampleda;
  formData.rptGroup = labMainInfoObj.rptGroup;
  if (!IsEmpty(formData.destructionTime) && formatDateTime(formData.destructionTime, 'yyyy-MM-dd') === '1900-01-01') {
    formData.destructionTime = '';
  }
  const url = IsEmpty(formData.id) ? '/bac-blood-cultrue/addBacBloodCultrue' : '/bac-blood-cultrue/updateBacBloodCultrue';
  proxy.$http
    .post(url, formData)
    .then((res: any) => {
    /*  if (res && res.status && res.status.code && res.status.code === 1) {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        /!* 记录过程记录 *!/
        const a = localStorage.getItem('userInfo');
        const b = JSON.parse(a);
        const cntStr = [!IsEmpty(formData.culMediumNa) ? '培养瓶:' + formData.culMediumNa + '' : '', !IsEmpty(formData.samplingSiteNa) ? '采样部位:' + formData.samplingSiteNa + '' : '', !IsEmpty(formData.weight) ? '重量:' + formData.weight + '' : '', !IsEmpty(formData.isPositive) ? '是否阳性:' + (formData.samplingSiteNa === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.result) ? '鉴定结果:' + formData.result + '' : '', !IsEmpty(formData.specialDesc) ? '特殊描述:' + formData.specialDesc + '' : '', !IsEmpty(formData.isAlarm) ? '危急值:' + (formData.isAlarm === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.alarmText) ? '危急值描述:' + formData.alarmText + '' : '', !IsEmpty(formData.isPollute) ? '标本污染:' + (formData.isPollute === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.instrNa) ? '培养箱:' + formData.instrNa + '' : '', !IsEmpty(formData.barcode) ? '容器条码:' + formData.barcode + '' : '', !IsEmpty(formData.bottleNo) ? '瓶号:' + formData.bottleNo + '' : '', !IsEmpty(formData.posInfo) ? '位置:' + formData.posInfo + '' : '', !IsEmpty(formData.state) ? '状态:' + formData.state + '' : '', !IsEmpty(formData.testTime) ? '开始培养时间:' + formData.testTime + '' : '', !IsEmpty(formData.resultTime) ? '结束培养时间:' + formData.resultTime + '' : '', !IsEmpty(formData.destructionTime) ? '销毁时间:' + formData.destructionTime + '' : '', !IsEmpty(formData.expoTime) ? '培养时长:' + formData.expoTime + '' : '']
          .filter(Boolean) // 过滤掉空字符串
          .join('\n');
        const strainNameStr = !IsEmpty(formData.culMediumNa) ? '培养瓶:' + formData.culMediumNa + '' : '';
        const processLogData = {
          strainId: null,
          strainNo: null,
          strainName: strainNameStr,
          maininfoId: labMainInfoObj.id,
          wkFlwId: null,
          wkFlwNodeId: null,
          rptGroup: labMainInfoObj.rptGroup,
          sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
          sampleNo: labMainInfoObj.sampleNo,
          testFlowNo: curCulBoxObj.testFlowNo,
          testNodeNo: 'YQPY',
          content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】保存培养结果\n${cntStr}`,
          operatorDoctor: IsEmpty(b.username) ? '' : b.username
        };
        saveProcessLogs(processLogData);
      }*/
      findBacBloodCultureResult();
      proxy.$emit('currentRow', labMainInfoObj);
    })
    .catch((err: any) => {});
}
/**切换培养瓶 */
function selectChangeCul(pi, i, m) {
  curCulBox;
  curCulBox.value = i;
  curParentCulBox.value = pi;
  Object.assign(curCulBoxObj, m);
  findBacBloodCultureResult();
}
/**加载培养瓶信息 */
function findBloodCulMediumList() {
  culMediumList.length = 0;
  const url = '/api/bac/bac-test-culture-medium/findBloodCulMediumList';
  let data = { sampleNo: labMainInfoObj.sampleNo, sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'), rptGroup: labMainInfoObj.rptGroup, reqNo: labMainInfoObj.reqNo, testFlowNo: '', testNodeNo: '', maininfoId: labMainInfoObj.id, bacTestResultId: bacTestResult.id } as any;
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      culMediumList.length = 0;
      if (res && res.data && res.data.length >= 0) {
        Object.assign(culMediumList, res.data);
        Object.assign(curCulBoxObj, res.data[0]);
        findBacBloodCultureResult();
      }
    })
    .catch((err: any) => {});
}
/**发布初级报告 */
async function rptFirstReport() {
  // if (IsEmpty(formData.testFlowNo)) {
  //   formData.testFlowNo = labMainInfoObj.testFlowNo;
  // }
  // BacFirstReportRef.value?.initPage(labMainInfoObj, formData, curCulBoxObj);

  //先保存  保存之后 查看是否有危急值
  formData.culMediumNo = curCulBoxObj.cultureNo;
  formData.sampleNo = labMainInfoObj.sampleNo; //样本号
  formData.sampleda = labMainInfoObj.sampleda;
  formData.rptGroup = labMainInfoObj.rptGroup;
  if (!IsEmpty(formData.destructionTime) && formatDateTime(formData.destructionTime, 'yyyy-MM-dd') === '1900-01-01') {
    formData.destructionTime = '';
  }
  const url = IsEmpty(formData.id) ? '/bac-blood-cultrue/addBacBloodCultrue' : '/bac-blood-cultrue/updateBacBloodCultrue';
  proxy.$http
    .post(url, formData)
    .then(async (res: any) => {
      if (res && res.status && res.status.code && res.status.code === 1) {
        //findBacBloodCultureResult();
        proxy.$emit('currentRow', labMainInfoObj);
        //查看是否有危急值
        if (formData && !IsEmpty(formData.id) && !IsEmpty(formData.isAlarm) && (formData.isAlarm === '1' || formData.isAlarm === 1)) {
          //是否还有未处理的危急值
          labMainInfoObj.cultureNo = curCulBoxObj.cultureNo;
          const criNotreat = await isNotreatAlarmReport(labMainInfoObj);
          if (criticalBloodReportRef.value && criNotreat) {
            criticalBloodReportRef.value?.criticaReportData(labMainInfoObj);
            return;
          }
        }
        //发布初级报告
        confirmSecReport();
      }
    })
    .catch((err: any) => {});
}

/**检查是否有未处理的危急值 */
function isNotreatAlarmReport(mainInfo) {
  return new Promise((resolve, reject) => {
    const url = '/bac-blood-cultrue/getAlarmResult';
    proxy.$http
      .get(url, {
        params: {
          maininfoId: mainInfo.id,
          rptGroup: mainInfo.rptGroup,
          sampleda: formatDateTime(mainInfo.sampleda, 'yyyy-MM-dd 00:00:00'),
          sampleNo: mainInfo.sampleNo,
          testFlowNo: '',
          testNodeNo: '',
          culMediumNo: mainInfo.cultureNo
        }
      })
      .then((res: any) => {
        if (res && res.data && res.data.length > 0) {
          resolve(true);
        } else {
          resolve(false);
        }
      })
      .catch((err) => {
        resolve(false);
      });
  });
}
/**双击结果文本框弹窗选择培养结果 */
function selectBloodCulResult() {
  bloodCulResultModal.value = true;
}

/**条码号回车事件 */
function barcodeKeyUp({ value, $event }) {
  if ($event.keyCode && $event.keyCode === 13) {
    saveBloodCultureInfo();
  }
}
/**转种 */
function transplantationClick() {
  culCombinaModal.value = true;
  findCulCombinaList();
}
/**培养基组合类型改变 */
function culCombinaSelectChange() {
  findCulCombinaList();
}
/**培养基组合关键字输入回车事件 */
function keyupEventByCulCombinaKeyValue({ value, $event }) {
  if ($event.keyCode && $event.keyCode === 13) {
    findCulCombinaList();
  }
}
/**加载培养基组合列表 */
function findCulCombinaList() {
  culCombinaLoading.value = true;
  culCombinaSelectList.length = 0;
  const url = '/api/bac/bac-cultrue-combination/findBacCultureCombinationList';
  let type = '2';
  if (!IsEmpty(culCombinaType.value) && (culCombinaType.value == '-1' || culCombinaType.value == -1)) {
    type = '';
  } else {
    type = culCombinaType.value;
  }
  let data = { searchValue: culCombinaSearchKeyValue.value, type: type } as any;
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      culCombinaSelectList.length = 0;
      if (res && res.data && res.data.length >= 0) {
        Object.assign(culCombinaSelectList, res.data);
        culCombinaTableRef.value?.setCurrentRow(culCombinaSelectList[0]);
      }
      culCombinaLoading.value = false;
    })
    .catch((err: any) => {
      culCombinaLoading.value = false;
    });
}
/**培养基组合确定选择事件 */
function culCombinaComfirm() {
  const row = culCombinaTableRef.value?.getCurrentRecord();
  proxy.$emit('subcultivation', row);

  // const url = '/bac-blood-cultrue/bloodCultureTransplantation';
  // let data = {
  //   rptGroup: labMainInfoObj.rptGroup,
  //   sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
  //   sampleNo: labMainInfoObj.sampleNo,
  //   reqNo: labMainInfoObj.reqNo,
  //   testFlowNo: labMainInfoObj.testFlowNo,
  //   testNodeNo: labMainInfoObj.nodeNo,
  //   parentId: culMediumList[curParentCulBox.value].id,
  //   bacCultureCombination: row
  // } as any;
  // proxy.$http
  //   .post(url, data)
  //   .then((res: any) => {
  //     if (res && res.data) {
  //       VxeMessage("成功", VxeNotifyType.success);
  //     }
  //     //加载
  //     findBacBloodCultureResult();
  //   })
  //   .catch((err: any) => {
  //     VxeMessage('失败', VxeNotifyType.error);
  //   });
}
/**工作单 */
function reprintLabel() {
  const url = '/api/lab/lab-rptmain/RePrintLabel';
  proxy.$http
    .get(url, { params: { sltWorkFlowNo: sltWorkFlowObj._value.workFlowNo } })
    .then(async (res: any) => {
      if (res.status && res.status.code === 1) {
        console.log('res======', res.data);
        printParamsObj.value = [
          {
            ReportName: res.data.reportId,
            ReportParameters: [
              { Name: 'reqNo', Value: labMainInfoObj.reqNo },
              { Name: 'Id', Value: labMainInfoObj.id }
            ],
            PdfPrinterSetting: { PdfPrinterCopies: 1 }
          }
        ];
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

/**补打标签 */
function printBarcodeLabel() {
  if (!formData || IsEmpty(formData.barcode)) {
    VxeMessage('容器条码为空', VxeNotifyType.error);
    return;
  }
  let url = `/api/pubReport/getReportByBusFormCode?code=006`;
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res && res.status && res.status.code === 1 && res.data && !IsEmpty(res.data.id)) {
        printParamsObj.value = [{ Id: new Date().valueOf(), ReportName: res.data.id, ReportParameters: [{ Name: 'Id', Value: curCulBoxObj.id }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];

        /* 记录过程记录 */
    /*    const a = localStorage.getItem('userInfo');
        const b = JSON.parse(a);
        const strainNameStr = !IsEmpty(formData.culMediumNa) ? '培养瓶:' + formData.culMediumNa + '' : '';
        const processLogData = {
          strainId: null,
          strainNo: null,
          strainName: strainNameStr,
          maininfoId: labMainInfoObj.id,
          wkFlwId: null,
          wkFlwNodeId: null,
          rptGroup: labMainInfoObj.rptGroup,
          sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
          sampleNo: labMainInfoObj.sampleNo,
          testFlowNo: curCulBoxObj.testFlowNo,
          testNodeNo: 'YQPY',
          content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】补打${!IsEmpty(formData.culMediumNa) ? '【' + formData.culMediumNa + '】' : ''}标签:${curCulBoxObj.barcode}`,
          operatorDoctor: IsEmpty(b.username) ? '' : b.username
        };
        saveProcessLogs(processLogData);*/
      } else {
        proxy.$alert('查无容器条码模板', '提示');
      }
    })
    .catch((err: any) => {
      proxy.$alert('查询容器条码模板失败', '提示');
      //VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
    });
  //printParamsObj.value = [{ Id: new Date().valueOf(), ReportName: '1779903240373112834', ReportParameters: [{ Name: 'code', Value: formData.barcode }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
}
/**双击选择菌落形态 */
function dblclickSelectObsers() {
  BacObserSelectionRef.value?.showModal(formData.morphologyName);
}
/**菌落形态确认选中 */
function obserConfirm(e) {
  let data = e.cultureMedium + '(' + e.morphology + ')';
  formData.obserDesc = data;
}
/**鉴定结果选中事件 */
function SelectRowClick1(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      formData[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  } else {
    e.aimKeys.forEach((m) => {
      formData[m.aimKey] = e.row[m.rowKey];
    });
  }
}
/**预览初级报告 */
function previewSecondRpt() {
  const arr = [];
  culMediumList.forEach((item) => {
    arr.push(item.cultureNo);
  });
  proxy.$emit('actionBtnsClick', { event: 'previewFirstRpt', paramObj: { testFlowNo: labMainInfoObj.testFlowNo, testNodeNo: labMainInfoObj.nodeNo, culMediumNos: arr } });
}
/**打印二级报告 */
function printSecondRpt() {
  const arr = [];
  culMediumList.forEach((item) => {
    arr.push(item.cultureNo);
  });
  proxy.$emit('actionBtnsClick', { event: 'printFirstRpt', paramObj: { testFlowNo: labMainInfoObj.testFlowNo, testNodeNo: labMainInfoObj.nodeNo, culMediumNos: arr } });
}
/**判断是否审核，若审核范围ture */
function resultIsDisabled() {
  if (!IsEmpty(labMainInfoObj) && labMainInfoObj.isChk == '2') {
    return true;
  } else {
    return false;
  }
}

/**危急值 */
function criticalClick() {
  labMainInfoObj.cultureNo = curCulBoxObj.cultureNo;
  criticalBloodReportRef.value?.criticaReportData(labMainInfoObj);
}
/**危急值处理完成 */
function alarmTreatFinish(data) {
  confirmSecReport();
  /* if (alarmReportBeforeChk.value && !chkBeforePrint.value) {
     $this['chkMainInfo']();
   }
   if (alarmReportBeforeChk.value && chkBeforePrint.value) {
     $this['previewPrint']();
   }*/
  try {
    /* 记录过程记录 */
    const a = localStorage.getItem('userInfo');
    const b = JSON.parse(a);
    const cntStrArr = [];
    data.forEach((itm) => {
      if (itm.criItem) {
        if (!IsEmpty(itm.criItem.culMediumNa)) {
          cntStrArr.push(`培养瓶:${itm.criItem.culMediumNa}`);
        }
        if (!IsEmpty(itm.criItem.barcode)) {
          cntStrArr.push(`容器条码:${itm.criItem.barcode}`);
        }
        if (!IsEmpty(itm.criItem.alarmText)) {
          cntStrArr.push(`危急值信息:${itm.criItem.alarmText}`);
        }
        if (!IsEmpty(itm.criItem.result)) {
          cntStrArr.push(`结果:${itm.criItem.result}`);
        }
      }
      if (itm.criData) {
        if (!IsEmpty(itm.criData.notifyPersonNa)) {
          cntStrArr.push(`通知医师:${itm.criData.notifyPersonNa}`);
        }
        if (!IsEmpty(itm.criData.reportPersonNa)) {
          cntStrArr.push(`发布人:${itm.criData.reportPersonNa}`);
        }
        if (!IsEmpty(itm.criData.notificationTypeNa)) {
          cntStrArr.push(`通知方式:${itm.criData.notificationTypeNa}`);
        }
        if (!IsEmpty(itm.criData.remark)) {
          cntStrArr.push(`备注:${itm.criData.remark}`);
        }
        if (!IsEmpty(itm.criData.isReTest)) {
          cntStrArr.push(`是否复查:${itm.criData.isReTest === 1 ? '是' : '否'}`);
        }
      }
      if (cntStrArr && cntStrArr.length > 0) {
        cntStrArr.push(`\n`);
      }
    });

    const cntStr = cntStrArr
      .filter(Boolean) // 过滤掉空字符串
      .join('\n');
    const processLogData = {
      strainId: null,
      strainNo: null,
      strainName: `发布危急值`,
      maininfoId: labMainInfoObj.id,
      wkFlwId: null,
      wkFlwNodeId: null,
      rptGroup: labMainInfoObj.rptGroup,
      sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
      sampleNo: labMainInfoObj.sampleNo,
      testFlowNo: curCulBoxObj.testFlowNo,
      testNodeNo: 'YQPY',
      content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布危急值\n${cntStr}`,
      operatorDoctor: IsEmpty(b.username) ? '' : b.username
    };
    saveProcessLogs(processLogData);
  } catch (error) {}
}

/**确认发布报告 */
function confirmSecReport() {
  const datas = [];
  const data = {
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: labMainInfoObj.sampleda + ' 00:00:00',
    sampleNo: labMainInfoObj.sampleNo,
    testFlowNo: labMainInfoObj.testFlowNo,
    testNodeNo: labMainInfoObj.nodeNo,
    culCombinaNo: curCulBoxObj.cultureCombinNo,
    culMediumNo: curCulBoxObj.cultureNo,
    bloodcultureId: formData.id,
    isCancel: 0,
    cancelDoctor: '',
    cancelReason: ''
  };
  datas.push(data);
  const url = '/api/bac/bac-publis-first-report/batchEditPublisFirstReport';
  proxy.$http
    .post(url, datas)
    .then((res: any) => {
      VxeMessage('发布成功', VxeNotifyType.success);
      findBacBloodCultureResult();
      try {
        /* 记录过程记录 */
        const a = localStorage.getItem('userInfo');
        const b = JSON.parse(a);
        const cntStr = [!IsEmpty(formData.culMediumNa) ? '培养瓶:' + formData.culMediumNa + '' : '', !IsEmpty(formData.samplingSiteNa) ? '采样部位:' + formData.samplingSiteNa + '' : '', !IsEmpty(formData.weight) ? '重量:' + formData.weight + '' : '', !IsEmpty(formData.isPositive) ? '是否阳性:' + (formData.samplingSiteNa === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.resultThreeDays) ? '鉴定结果:' + formData.resultThreeDays + '' : '', !IsEmpty(formData.specialDesc) ? '特殊描述:' + formData.specialDesc + '' : '', !IsEmpty(formData.isAlarm) ? '危急值:' + (formData.isAlarm === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.alarmText) ? '危急值描述:' + formData.alarmText + '' : '', !IsEmpty(formData.isPollute) ? '标本污染:' + (formData.isPollute === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.instrNa) ? '培养箱:' + formData.instrNa + '' : '', !IsEmpty(formData.barcode) ? '容器条码:' + formData.barcode + '' : '', !IsEmpty(formData.bottleNo) ? '瓶号:' + formData.bottleNo + '' : '', !IsEmpty(formData.posInfo) ? '位置:' + formData.posInfo + '' : '', !IsEmpty(formData.state) ? '状态:' + formData.state + '' : '', !IsEmpty(formData.testTime) ? '开始培养时间:' + formData.testTime + '' : '', !IsEmpty(formData.resultTime) ? '结束培养时间:' + formData.resultTime + '' : '', !IsEmpty(formData.destructionTime) ? '销毁时间:' + formData.destructionTime + '' : '', !IsEmpty(formData.expoTime) ? '培养时长:' + formData.expoTime + '' : '']
            .filter(Boolean) // 过滤掉空字符串
            .join('\n');
        const strainNameStr = !IsEmpty(formData.culMediumNa) ? '培养瓶:' + formData.culMediumNa + '' : '';
        const processLogData = {
          strainId: null,
          strainNo: null,
          strainName: strainNameStr,
          maininfoId: labMainInfoObj.id,
          wkFlwId: null,
          wkFlwNodeId: null,
          rptGroup: labMainInfoObj.rptGroup,
          sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
          sampleNo: labMainInfoObj.sampleNo,
          testFlowNo: curCulBoxObj.testFlowNo,
          testNodeNo: 'YQPY',
          content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布初级报告\n${cntStr}`,
          operatorDoctor: IsEmpty(b.username) ? '' : b.username
        };
        saveProcessLogs(processLogData);
      } catch (error) {
        console.log('错误', error);
      }
    })
    .catch((err: any) => {
      VxeMessage('发布失败', VxeNotifyType.error);
    });
}

function cancelSecReport() {
  const datas = [];
  const data = {
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: labMainInfoObj.sampleda + ' 00:00:00',
    sampleNo: labMainInfoObj.sampleNo,
    testFlowNo: labMainInfoObj.testFlowNo,
    testNodeNo: labMainInfoObj.nodeNo,
    culCombinaNo: curCulBoxObj.cultureCombinNo,
    culMediumNo: curCulBoxObj.cultureNo,
    bloodcultureId: formData.id,
    isCancel: 0,
    cancelDoctor: '',
    cancelReason: ''
  };
  datas.push(data);
  const url = '/api/bac/bac-publis-first-report/batchCancelFirstReport';
  proxy.$http
    .post(url, datas)
    .then((res: any) => {
      VxeMessage('撤销成功', VxeNotifyType.success);
      VxeMessage(res.status.msg, VxeNotifyType.success);
      /* 记录过程记录 */
      const a = localStorage.getItem('userInfo');
      const b = JSON.parse(a);
      const cntStr = [!IsEmpty(formData.culMediumNa) ? '培养瓶:' + formData.culMediumNa + '' : '', !IsEmpty(formData.samplingSiteNa) ? '采样部位:' + formData.samplingSiteNa + '' : '', !IsEmpty(formData.weight) ? '重量:' + formData.weight + '' : '', !IsEmpty(formData.isPositive) ? '是否阳性:' + (formData.samplingSiteNa === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.resultThreeDays) ? '鉴定结果:' + formData.resultThreeDays + '' : '', !IsEmpty(formData.specialDesc) ? '特殊描述:' + formData.specialDesc + '' : '', !IsEmpty(formData.isAlarm) ? '危急值:' + (formData.isAlarm === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.alarmText) ? '危急值描述:' + formData.alarmText + '' : '', !IsEmpty(formData.isPollute) ? '标本污染:' + (formData.isPollute === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.instrNa) ? '培养箱:' + formData.instrNa + '' : '', !IsEmpty(formData.barcode) ? '容器条码:' + formData.barcode + '' : '', !IsEmpty(formData.bottleNo) ? '瓶号:' + formData.bottleNo + '' : '', !IsEmpty(formData.posInfo) ? '位置:' + formData.posInfo + '' : '', !IsEmpty(formData.state) ? '状态:' + formData.state + '' : '', !IsEmpty(formData.testTime) ? '开始培养时间:' + formData.testTime + '' : '', !IsEmpty(formData.resultTime) ? '结束培养时间:' + formData.resultTime + '' : '', !IsEmpty(formData.destructionTime) ? '销毁时间:' + formData.destructionTime + '' : '', !IsEmpty(formData.expoTime) ? '培养时长:' + formData.expoTime + '' : '']
          .filter(Boolean) // 过滤掉空字符串
          .join('\n');
      const strainNameStr = !IsEmpty(formData.culMediumNa) ? '培养瓶:' + formData.culMediumNa + '' : '';
      const processLogData = {
        strainId: null,
        strainNo: null,
        strainName: strainNameStr,
        maininfoId: labMainInfoObj.id,
        wkFlwId: null,
        wkFlwNodeId: null,
        rptGroup: labMainInfoObj.rptGroup,
        sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
        sampleNo: labMainInfoObj.sampleNo,
        testFlowNo: curCulBoxObj.testFlowNo,
        testNodeNo: 'YQPY',
        content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】撤销报告\n${cntStr}`,
        operatorDoctor: IsEmpty(b.username) ? '' : b.username
      };
      saveProcessLogs(processLogData);
      findBacBloodCultureResult();
    })
    .catch((err: any) => {
      VxeMessage('撤销失败', VxeNotifyType.error);
    });
}
/**阴性结果 */
function negativeResult() {
  RptResultBacFormRef.value?.showModal(labMainInfoObj, false);
}
/**血培养阴性结果确认保存 */
function bacTestResultConfirmSave(e) {
  rptResultBacEditClosed({ row: e });
}
/**细菌结果列表关闭编辑状态 */
function rptResultBacEditClosed({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  row.testFlowNo = labMainInfoObj.testFlowNo;
  row.testNodeNo = labMainInfoObj.nodeNo;
  row.sampleda = labMainInfoObj.sampleda;
  if (IsEmpty(row.culMediumNo)) {
    row.culMediumNo = curCulBoxObj.cultureNo;
  }
  let url = `/api/bac/bac-test-result/${row && !IsEmpty(row.id) ? 'updateBacTestResult' : 'addBacTestResult'}`;
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      VxeMessage('操作成功', VxeNotifyType.success);
      proxy.$forceUpdate();

      try {
        /* 记录过程记录 */
        const a = localStorage.getItem('userInfo');
        const b = JSON.parse(a);
        const cntStr = [!IsEmpty(row.germNa) ? '结果:' + row.germNa + '' : '', !IsEmpty(row.testResult) ? '结果描述:' + row.testResult + '' : '', !IsEmpty(row.descText) ? '专家评语:' + row.descText + '' : '']
          .filter(Boolean) // 过滤掉空字符串
          .join('\n');
        const processLogData = {
          strainId: null,
          strainNo: null,
          strainName: `发布阴性报告`,
          wkFlwId: null,
          wkFlwNodeId: null,
          rptGroup: row.rptGroup,
          sampleda: formatDateTime(row.sampleda, 'yyyy-MM-dd 00:00:00'),
          sampleNo: row.sampleNo,
          testFlowNo: curCulBoxObj.testFlowNo,
          testNodeNo: 'YQPY',
          content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布阴性结果报告\n${cntStr}`,
          operatorDoctor: IsEmpty(b.username) ? '' : b.username
        };
        saveProcessLogs(processLogData);
      } catch (error) {}
    })
    .catch((err: any) => {
      //ToDo
    });
}
/**危急值 */
function remarkConfirm(value) {
  formData.alarmText = value;
}
/**采样部位 */
function dropSelectConfirm(e) {
  e.aimKeys.forEach((item) => {
    formData[item.targetField] = e.row[item.sourceField];
  });
}
/**计算培养时间时间差 */
function expoTimeDiffChange() {
  let s = IsEmpty(formData.testTime) ? labMainInfoObj.testTime : formData.testTime;
  let e = IsEmpty(formData.resultTime) ? formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss') : formData.resultTime;
  let diffObj = calculateTimeDifference(s, e);
  formData.expoTime = `${!IsEmpty(diffObj.days) ? diffObj.days + '天' : ''}${!IsEmpty(diffObj.hours) ? diffObj.hours + '时' : ''}${!IsEmpty(diffObj.minutes) ? diffObj.minutes + '分' : ''}`;
}
/** 初级报告发布历史 */
function rptFirstReportHistory() {
  BacFirstReportHistoryRef.value?.initPage(labMainInfoObj, formData, curCulBoxObj);
}

// 弹框取消按钮
function closeDialog() {
  dialog.value = false;
}

function openDialog() {
  getCultureDetail();
  dialog.value = true;
}

// 加载培养基
function getCultureDetail() {
  if (!labMainInfoObj.reqNo) {
    return;
  }
  cultureTableList.length = 0;
  lloading.value = true;
  const url = '/api/bac/bac-test-culture-medium/findBacTestCultureMediumList';
  proxy.$http
    .get(url, { params: { reqNo: labMainInfoObj.reqNo } })
    .then(async (res: any) => {
      Object.assign(cultureTableList, res.data);
      //默认全选
      proxy.$nextTick(() => {
        const $xTable = proxy.$refs.cultureTableRef as any;
        if (cultureTableList && cultureTableList.length > 0) {
          $xTable.setCheckboxRow(cultureTableList, true);
          //$xTable.updateFooter(); // 在值发生改变时更新表尾合计(一开始获取页面信息时调用计算表尾方法)
        }
      });

      lloading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function printLabel() {
  const selectRows = (proxy.$refs.cultureTableRef as any).getCheckboxRecords();
  let reportId;
  if (selectRows.length > 0) {
    let url = `/api/pubReport/getReportByBusFormCode?code=006`;
    proxy.$http
      .get(url)
      .then((res: any) => {
        if (res && res.status && res.status.code === 1 && res.data && !IsEmpty(res.data.id)) {
          reportId = res.data.id;
          let i = 0;
          selectRows.forEach((sltRow: any) => {
            if (!sltRow.isPrintLabels) {
              let num = 1;
              let report = reportId;
              if (!IsEmpty(sltRow.tagsNum)) {
                num = sltRow.tagsNum;
              }
              if (!IsEmpty(sltRow.mediumTag)) {
                report = sltRow.mediumTag;
              }
              const param = [{ ReportName: report, ReportParameters: [{ Name: 'code', Value: labMainInfoObj.reqNo }], PdfPrinterSetting: { PdfPrinterCopies: num } }];
              setTimeout(() => {
                quietPrintRef.value?.print2(param);
              }, i * 100);
              i++;
            }
          });
          //printParamsObj.value = [{ ReportName: reportId, ReportParameters: [{ Name: 'id', Value: labMainInfoObj.reqNo }], PdfPrinterSetting: { PdfPrinterCopies: selectRows.length } }];
        } else {
          proxy.$alert('查无报告模板', '提示');
        }
      })
      .catch((err: any) => {
        proxy.$alert('查询报告模板失败', '提示');
        //VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
      });
  }
  dialog.value = false;
}
function publish72NoGermReport() {
  publish72Loading.value = true;
  formData.culMediumNo = curCulBoxObj.cultureNo;
  formData.sampleNo = labMainInfoObj.sampleNo; //样本号
  formData.sampleda = labMainInfoObj.sampleda;
  formData.rptGroup = labMainInfoObj.rptGroup;
  formData.reqNo = labMainInfoObj.reqNo;
  formData.testFlowNo = curCulBoxObj.testFlowNo;
  formData.testNodeNo = 'YQPY';

  const a = getOptionValueByCodeRptGroupOption('publish72hnogermreport');
  if (!IsEmpty(a)) {
    formData.resultThreeDays = a;
  } else {
    formData.resultThreeDays = '血培养经过三天培养无细菌生长';
  }
  //formData.bacPublishStatus = 1;
  const url = '/bac-blood-cultrue/publish72NoGermReport';
  proxy.$http
    .post(url, formData)
    .then((res: any) => {
      if (res && res.status && res.status.code && res.status.code === 1) {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        /* 记录过程记录 */
        const a = localStorage.getItem('userInfo');
        const b = JSON.parse(a);
        const cntStr = [!IsEmpty(formData.culMediumNa) ? '培养瓶:' + formData.culMediumNa + '' : '', !IsEmpty(formData.samplingSiteNa) ? '采样部位:' + formData.samplingSiteNa + '' : '', !IsEmpty(formData.weight) ? '重量:' + formData.weight + '' : '', !IsEmpty(formData.isPositive) ? '是否阳性:' + (formData.samplingSiteNa === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.resultThreeDays) ? '鉴定结果:' + formData.resultThreeDays + '' : '', !IsEmpty(formData.specialDesc) ? '特殊描述:' + formData.specialDesc + '' : '', !IsEmpty(formData.isAlarm) ? '危急值:' + (formData.isAlarm === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.alarmText) ? '危急值描述:' + formData.alarmText + '' : '', !IsEmpty(formData.isPollute) ? '标本污染:' + (formData.isPollute === 1 ? '是' : '否') + '' : '', !IsEmpty(formData.instrNa) ? '培养箱:' + formData.instrNa + '' : '', !IsEmpty(formData.barcode) ? '容器条码:' + formData.barcode + '' : '', !IsEmpty(formData.bottleNo) ? '瓶号:' + formData.bottleNo + '' : '', !IsEmpty(formData.posInfo) ? '位置:' + formData.posInfo + '' : '', !IsEmpty(formData.state) ? '状态:' + formData.state + '' : '', !IsEmpty(formData.testTime) ? '开始培养时间:' + formData.testTime + '' : '', !IsEmpty(formData.resultTime) ? '结束培养时间:' + formData.resultTime + '' : '', !IsEmpty(formData.destructionTime) ? '销毁时间:' + formData.destructionTime + '' : '', !IsEmpty(formData.expoTime) ? '培养时长:' + formData.expoTime + '' : '']
          .filter(Boolean) // 过滤掉空字符串
          .join('\n');
        const strainNameStr = !IsEmpty(formData.culMediumNa) ? '培养瓶:' + formData.culMediumNa + '' : '';
        const processLogData = {
          strainId: null,
          strainNo: null,
          strainName: strainNameStr,
          maininfoId: labMainInfoObj.id,
          wkFlwId: null,
          wkFlwNodeId: null,
          rptGroup: labMainInfoObj.rptGroup,
          sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
          sampleNo: labMainInfoObj.sampleNo,
          testFlowNo: curCulBoxObj.testFlowNo,
          testNodeNo: 'YQPY',
          content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】72小时无菌发布\n${cntStr}`,
          operatorDoctor: IsEmpty(b.username) ? '' : b.username
        };
        saveProcessLogs(processLogData);
      }
      publish72Loading.value = false;
      findBacBloodCultureResult();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      publish72Loading.value = false;
    });
}
</script>

<style scoped lang="scss">
@import '@/assets/css/el-tabs.scss';

#bacTestResult {
  height: 100%;
}

.lab-bac-test-result-tab {
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  :deep(.el-tabs__nav-prev) {
    line-height: 28px !important;
  }

  :deep(.el-tabs__nav-next) {
    line-height: 28px !important;
  }

  :deep(.el-tabs__content) {
    height: 0px;
    padding: 2px;
  }

  :deep(.el-tab-pane) {
    height: 0px;
  }
}

:deep(.cell-bgColor) {
  .vxe-cell {
    height: 100%;
  }
}

.form-panel {
  :deep(.vxe-input--inner) {
    border-radius: 4px !important;
  }
}

/* 定义父容器的样式 */
.grid-container {
  display: grid;
  /* 行列的间距（可根据需要调整） */
  gap: 2px;
  /* 根据需要设定最小的列宽和行高 */
  ///min-width: 10px;
  //min-height: 10px;
  //grid-template-columns: repeat(3, 1fr);
  /* 自动计算列数和行数 */
  grid-template-columns: repeat(10, auto);
  //grid-template-rows: repeat(auto-fit, minmax(min-height, auto));
}

/* 定义子项的样式 */
.grid-item {
  /* 这里设置了子项的基础样式 */
  background-color: #e2e2e2; //#4caf50
  color: white;
  text-align: center;
  padding: 2px;
  border-radius: 0px;
  cursor: pointer;
  //font-size: clamp(0.1rem, 0.5rem, 2rem); /* 根据容器大小动态调整字体大小 */
  //text-align: center;
}

.active {
  background-color: #4caf50;
}

/* 定义培养瓶容器的样式 */
.bottle {
  cursor: pointer;
  width: 40px;
  /* 瓶子的宽度 */
  height: 70px;
  /* 瓶子的高度 */
  background: linear-gradient(to top, #f5f5f5 50%, #fff);
  /* 瓶子的渐变效果 */
  border-radius: 75px 75px 20px 20px;
  /* 瓶子的圆角 */
  border: 2px solid #ccc;
  /* 瓶子的边框 */
  position: relative;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  /* 瓶子的阴影 */
  display: flex;
  align-items: center;
  justify-content: center;

  .select-active {
    position: absolute;
    bottom: 0px;
    right: -5px;
    content: '选';
  }
}

/* 定义瓶口的样式 */
.bottle::before {
  content: '';
  position: absolute;
  top: -10px;
  /* 瓶口的位置 */
  left: 50%;
  width: 25px;
  height: 10px;
  background: #f5f5f5;
  /* 瓶口的颜色 */
  border-radius: 50% 50% 0 0;
  transform: translateX(-50%);
  border: 2px solid #ccc;
  /* 瓶口的边框 */
}

/* 定义瓶内液体的样式 */
.liquid {
  width: 100%;
  height: 50%;
  /* 液体的高度 */
  background: #87cefa;
  /* 液体的颜色 */
  border-radius: 0 0 4px 4px;
  /* 液体的圆角 */
  position: absolute;
  bottom: 0;
  left: 0;
}

/* 定义培养瓶容器的样式 */
.bottle-chld {
  cursor: pointer;
  width: 30px;
  /* 瓶子的宽度 */
  height: 55px;
  /* 瓶子的高度 */
  background: linear-gradient(to top, #f5f5f5 50%, #fff);
  /* 瓶子的渐变效果 */
  border-radius: 45px 45px 15px 15px;
  /* 瓶子的圆角 */
  border: 2px solid #ccc;
  /* 瓶子的边框 */
  position: relative;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  /* 瓶子的阴影 */
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 15px;

  .select-active {
    position: absolute;
    bottom: 0px;
    right: -5px;
    content: '选';
  }
}

/* 定义瓶口的样式 */
.bottle-chld::before {
  content: '';
  position: absolute;
  top: -8px;
  /* 瓶口的位置 */
  left: 50%;
  width: 20px;
  height: 8px;
  background: #f5f5f5;
  /* 瓶口的颜色 */
  border-radius: 50% 50% 0 0;
  transform: translateX(-50%);
  border: 2px solid #ccc;
  /* 瓶口的边框 */
}

/* 定义瓶内液体的样式 */
.liquid-chld {
  width: 100%;
  height: 50%;
  /* 液体的高度 */
  background: #87cefa;
  /* 液体的颜色 */
  border-radius: 0 0 4px 4px;
  /* 液体的圆角 */
  position: absolute;
  bottom: 0;
  left: 0;
}

.selected-box {
  border-radius: 10px;
}

.selected-box-active {
  background-color: $background-color-green;
}

.img-no-drag {
  pointer-events: none;
}

.no-edit {
  user-select: none;
  /* 禁止选择文本 */
  pointer-events: none;
  /* 禁止所有鼠标事件 */
}

:deep(.vxe-textarea--inner) {
  border-radius: 4px;
}

/* 基本样式 */
.petri-dish {
  cursor: pointer;
  width: 38px;
  height: 38px;
  background-color: #f0f0f0;
  /* 背景颜色 */
  border-radius: 50%;
  /* 圆形边框 */
  border: 8px solid #fff;
  /* 圆形边框的颜色 */
  position: relative;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;

  .select-active {
    position: absolute;
    bottom: 0px;
    right: -5px;
    content: '选';
  }
}
</style>
